package edu.zjucst.spb.util;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import edu.zjucst.spb.dao.spbuser.SpbUserDao;
import edu.zjucst.spb.domain.entity.EmailDTO;
import edu.zjucst.spb.domain.entity.SpbUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * 邮件通知工具
 *
 * @author MrLi
 * @date 2023-05-26 19:57
 **/
@Service
@Slf4j
public class EmailManager {
    @Value("${spring.mail.username}")
    private String fromMail;

    @Autowired
    private JavaMailSender javaMailSender;

    @Async
    public void sendSimpleMail(EmailDTO mailDTO) {
        // 简单邮件直接构建一个 SimpleMailMessage 对象进行配置并发送即可
        SimpleMailMessage simpMsg = new SimpleMailMessage();
        simpMsg.setFrom(fromMail);
        simpMsg.setTo(mailDTO.getToMail());
        if (mailDTO.getCc() != null) {
            simpMsg.setCc(mailDTO.getCc());
        }
        simpMsg.setSubject(mailDTO.getSubject());
        simpMsg.setText(mailDTO.getContent());
        try {
            javaMailSender.send(simpMsg);
        } catch (Exception e) {
            System.out.println("error: " + e.toString());
        }
    }

    @Autowired
    private SpbUserDao spbUserDao;

    @Async
    public void sendSimpleMail(Long toUserId, String title, String content) {
        SpbUser spbUser = spbUserDao.selectOne(new LambdaQueryWrapper<SpbUser>().eq(SpbUser::getId, toUserId));
        if (spbUser == null) {
            log.error("给{}发送邮件: {} - 失败", toUserId, title);
        }
        // 简单邮件直接构建一个 SimpleMailMessage 对象进行配置并发送即可
        SimpleMailMessage simpMsg = new SimpleMailMessage();
        simpMsg.setFrom(fromMail);
        assert !StringUtils.isEmpty(spbUser.getEmail());
        simpMsg.setTo(spbUser.getEmail());
        simpMsg.setSubject(title);
        simpMsg.setText(content);

        try {
            javaMailSender.send(simpMsg);
            log.info("Send email to {} success", toUserId);
        } catch (Exception e) {
            log.warn("Send email to {} error: {}", toUserId, e.toString());
        }
    }
}

